<template>
    <div class="main" style="background-image: url('https://javastuder-file-1258983147.cos.ap-shanghai.myqcloud.com/static/static-file/deskback.jpg')">
        <div class="login">
            <el-form
                    label-position="left"
                    size="small"
                    :model="ruleForm"
                    status-icon
                    :rules="rules"
                    ref="ruleForm"
                    label-width="70px"
                    class="login-form">
                <h3 class="title">中控平台</h3>
                <el-form-item label="账号" prop="account">
                    <el-input type="text" v-model="ruleForm.account" autocomplete="off"  placeholder="账号" >
                    </el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" show-password v-model="ruleForm.password" autocomplete="off"  placeholder="密码" >
                    </el-input>
                </el-form-item>
              <el-form-item label="验证码" prop="checkCode" v-if="needCheckCodeFlag">
                <el-col :span="15">
                  <el-input
                      type="text"
                    placeholder="请输入验证码"
                    v-model="ruleForm.checkCode">
                  </el-input>
                </el-col>
                <el-col :span="4" style="margin-left: 10px">
                  <div class="login-code" width="100%" @click="refreshCode">
                    <!--验证码组件-->
                    <dentify :identifyCode="identifyCode"></dentify></div>
                </el-col>
              </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm('ruleForm')" style="width:270px" :loading="loginLoading">登陆</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>


<script>
    import { login,needCheckCode } from '@/api/user';
    import dentify from "@v/user/CheckCode.vue";
    export default {
        components: {
          dentify,
        },
        data() {
            //验证用户名
            var validateAccount = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入用户名'));
                }else{
                    callback();
                }
            };
            //验证密码方法
            var validatePassword = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                }else{
                    callback();
                }
            };
            //验证密码方法
            var validateCheckCode = (rule, value, callback) => {
              if(!this.needCheckCodeFlag){
                return;
              }
              if (value === '') {
                callback(new Error('请输入验证码'));
              }else{
                if(value !== this.identifyCode){
                  callback(new Error('验证码输入错误'));
                  this.refreshCode();
                  return;
                }
                callback();
              }
            };
            return {
                loginLoading:false,
                needCheckCodeFlag:false,
                identifyCodes: "1234567890abcdefjhijklinopqrsduvwxyz", //随机串内容,从这里随机抽几个显示验证码
                identifyCode: "", //验证码图片内容
                //表单数据
                ruleForm: {
                    //用户名
                    account:'',
                    //密码
                    password: '',
                    checkCode:""
                },
                //表单验证数据
                rules: {
                    account: [
                        { validator: validateAccount, trigger: 'blur' }
                    ],
                    password: [
                        { validator: validatePassword, trigger: 'blur' }
                    ],
                    checkCode: [
                      { validator: validateCheckCode, trigger: 'blur' }
                    ],

                }
            };
        },
        mounted() {
          // 初始化验证码
          this.identifyCode = "";
          //参数：（1）随机串内容。（2）验证码显示位数
          this.makeCode(this.identifyCodes, 4);
          this.needCheckCodeQuery();
        },
        methods: {
          async needCheckCodeQuery(){
            let result = await needCheckCode();
            this.needCheckCodeFlag = result.data;
          },
          //表单提交
          submitForm: function (formName) {
            this.loginLoading = true;
            this.$refs[formName].validate(async (valid) => {
              //表单数据是否验证成功
              if (valid) {
                //调用登陆接口实现
                let result = await login(this.ruleForm);
                if (result.code != null && result.code === '200') {
                  let token = result.data.token;
                  window.localStorage.setItem("token", token);
                  if(result.data.needChangePassFlag != null && !result.data.needChangePassFlag){
                     this.$router.push("/")
                  }else{
                    this.$message.warning("密码已过期,请重新设置密码!")
                    this.$router.push("/changePassword")
                  }
                }else if(result.code != null && result.code === '100'){
                  this.$message.error(result.data.message)
                  this.needCheckCodeFlag = result.data.needCheckCodeFlag;
                  this.refreshCode();
                }
                this.loginLoading = false;
              } else {
                console.log('error submit!!');
                return false;
              }
            });
          },
          // 重置验证码
          refreshCode() {
            this.identifyCode = "";
            this.makeCode(this.identifyCodes, 4);
          },
          //获取验证码的值
          makeCode(o, l) {
            for (let i = 0; i < l; i++) {
              //通过循环获取字符串内随机几位
              this.identifyCode +=
                  this.identifyCodes[this.randomNum(0, this.identifyCodes.length)];
            }
          },
          //随机数字：用于当角标拿字符串的值
          randomNum(min, max) {
            return Math.floor(Math.random() * (max - min) + min);
          }
        }
    }
</script>

<style scoped lang="scss">
    .main{
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
        position: relative;
        .login{
            width: 300px;
            height: 230px;
            border: 0px solid #ccc;
            position: absolute;
            z-index: 999;
        }
    }
    .lang-container {
        position: absolute;
        top: 30px;
        right: 30px;
    }
    .title {
        margin: 0px auto 30px auto;
        text-align: center;
        color: #707070;
    }
    .login-form {
        border-radius: 6px;
        background: #ffffff;
        width: 340px;
        border: 0px solid #ccc;
        padding: 25px 25px 5px 25px;
        .el-input {
            height: 38px;
            input {
                height: 38px;
            }
        }
        .input-icon {
            height: 39px;
            width: 14px;
            margin-left: 2px;
            padding-bottom: 10px;
        }
    }
</style>